package com.open.api.peekapi.event;

import com.jfinal.plugin.activerecord.ActiveRecordPlugin;
import org.slf4j.LoggerFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;

import javax.sql.DataSource;

/**
 * Created by mengdexuan on 2017/5/18 17:59.
 */
public class DealWithStartedEvent implements ApplicationListener<ContextRefreshedEvent> {

	private static org.slf4j.Logger log = LoggerFactory.getLogger(DealWithStartedEvent.class);
	private ActiveRecordPlugin arp = null;

	@Override
	public void onApplicationEvent(ContextRefreshedEvent contextRefreshedEvent) {
		ApplicationContext appContext = contextRefreshedEvent.getApplicationContext();

		DataSource ds = appContext.getBean(DataSource.class);

		//JFinal ActiveRecordPlugin 插件配置
		arp = new ActiveRecordPlugin(ds);
		arp.start();
		close();

		log.info("项目启动完毕。");
	}


	public void close(){
		Runtime.getRuntime().addShutdownHook(new Thread(){
			public void run() {
				log.info("jvm 关闭，触发钩子函数……");
				if (arp!=null)arp.stop();
			}
		});
	}
}
